/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cursoexperto.jftf.view;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author Jose Fernando
 */
public class NifValidator implements Validator {

    private static final String NIF_STRING_ASOCIATION = "TRWAGMYFPDXBNJZSQVHLCKE";

    public NifValidator() {
    }
        /**
     * Valida el NIF, comprobando la longitud y vlaidando la letra
     */
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String enteredNIF = (String) value;
        int enteredNIFint = 0;
        char letraNIF = 0;
        if (enteredNIF.length() != 9) {
            FacesMessage message = new FacesMessage();
            message.setDetail("NIF no valido");
            message.setSummary("NIF no valido");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message);
        } else {
            try {
                enteredNIFint = Integer.valueOf(enteredNIF.substring(0, 8)).intValue();
                letraNIF = enteredNIF.substring(8).toUpperCase().charAt(0);
            } catch (NumberFormatException e) {
                FacesMessage message = new FacesMessage();
                message.setDetail("NIF no valido");
                message.setSummary("NIF no valido");
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message);
            }
            if (letraNIF != NIF_STRING_ASOCIATION.charAt(enteredNIFint % 23)) {
                FacesMessage message = new FacesMessage();
                message.setDetail("Letra NIF no valida");
                message.setSummary("Letra NIF no valida");
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message);
            }
        }
    }
}
